//
//  OffLineViewController.m
//  xpkc
//
//  Created by wanmeizty on 14-8-18.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "OffLineViewController.h"

@interface OffLineViewController ()

@end

@implementation OffLineViewController{
    /**
     *  下载完成数组（存放下载完成的视频或者组别）
     */
    NSMutableArray *downloadedArray;
    /**
     *  下载中数组
     */
    NSMutableArray *downloadingArray;
    /**
     *  下载中cell的数组
     */
    NSMutableArray *downloadingCellArray;
    /**
     *  主计时器（自动下载等操作的需求）
     */
    NSTimer *timer;
    /**
     *  检查网络的计时器（判断是否可以下载等）
     */
    NSTimer *netTimer;
    /**
     *  标记是否有下载中的
     */
    BOOL hadDownloading;
    /**
     *  wifi下标签，判断是否可以下载
     */
    BOOL WIFI;
    /**
     * 当点击下载离线视频时，离线页面根据是否有正在下载的视频选择跳转页面；当点击观看视频时，离线页面跳转到已经下载完成的页面
     */
    NSInteger tmp;
    /**
     竖线和豆豆
     */
    UILabel *pointLabel;
    int open[128];
    /**
     *  后台任务标记
     */
    UIBackgroundTaskIdentifier backTaskId;
    BOOL foreground;
    /**
     *  后台任务block
     */
    dispatch_block_t backgroundBlock;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.navigationItem.title = @"离线观看";
        self.tabBarItem.title = @"离线";
        self.tabBarItem.image =[UIImage imageNamed:@"offline"];
        if (IsIOS7) {
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"offline_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
        /**
         初始化需要，在视图加载之前
         */
        //初始化数组
        downloadedArray = [[NSMutableArray alloc]init];
        downloadingArray = [[NSMutableArray alloc]init];
        downloadingCellArray = [NSMutableArray array];
        for (int i = 0; i<128; i++) {
            open[i] = 1;//默认1为展开
        }
        //获取本地数据
        [self getDownloadedAndDownloadingItems];
        //注册通知接收
        tmp = 0;
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changetmp) name:START_DOWNLOAD_NOTIFICATION object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addDownloadQueue:) name:START_DOWNLOAD_NOTIFICATION object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deleteAllMeidas:) name:CLEAR_DATA_REFRESH_TABLEVIEW object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(saveDate:) name:SAVE_DATA_WHEN_EXIT object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(enterBackground:) name:UIApplicationDidEnterBackgroundNotification object:[UIApplication sharedApplication]];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(enterForeground:) name:UIApplicationWillEnterForegroundNotification object:[UIApplication sharedApplication]];
        //启动网络检查
        [self addNetTimer];
        //创建列表
        [self creatOfflineView];
        //创建导航栏
        [self creatNaviItem];
        
        [self performSelector:@selector(addTimer) withObject:nil afterDelay:2];
    }
    return self;
}
-(void)changetmp{
    tmp=0;
}
/**
 *  加载之后
 */
- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IsIOS7) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    
    //启动计时器
    if (WIFI&&downloadingArray.count>0) {
        [self performSelector:@selector(addTimer) withObject:nil afterDelay:1];
    }
}
/**
 *  视图出现
 *
 *  @param animated 是否动态
 */
- (void)viewWillAppear:(BOOL)animated{
    logdebug(@"视图出现");
    //刷新视图
    if (tmp==0) {
        [self firstView];
    }else{
        self.offlineView.segmentController.selectedSegmentIndex = 0;
        self.offlineView.downloadingTableView.hidden = YES;
        self.offlineView.downloadedTableView.hidden = NO;
    }
    //获取账号信息
    NSString *userMid =
    [[NSUserDefaults standardUserDefaults] valueForKey:USERMID_REMBER];
    logdebug(@"%@",userMid);
}
/**
 *  创建视图
 */
-(void)creatOfflineView{
    //添加视图
    self.offlineView = [[OffLineView alloc]initWithFrame:self.view.bounds];
    self.offlineView.downloadedTableView.delegate = self;
    self.offlineView.downloadedTableView.dataSource = self;
    self.offlineView.downloadedTableView.tag = 100;
    self.offlineView.downloadingTableView.delegate = self;
    self.offlineView.downloadingTableView.dataSource = self;
    self.offlineView.downloadingTableView.tag = 101;
    //默认显示下载中的
    self.offlineView.segmentController.selectedSegmentIndex = 1;
    //下载中界面
    //隐藏下载完成界面
    self.offlineView.downloadedTableView.hidden = YES;
    //根据列表的数量是否显示界面
    if (downloadingArray.count>0) {
        self.offlineView.downloadingTableView.hidden = NO;
    }else{
        self.offlineView.downloadingTableView.hidden = YES;
        self.offlineView.noteLabel.text = @"下载队列为空";
    }
    [self.offlineView.segmentController addTarget:self action:@selector(segmentChanged) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.offlineView];
    logdebug(@"创建视图");
    [self.offlineView.downloadingTableView reloadData];
}
/**
 *  创建导航栏菜单
 */
-(void)creatNaviItem{
    UIImage *backimg = [UIImage imageNamed:@"back1"];
    if (IsIOS7) {
        backimg = [backimg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    UIBarButtonItem *backitem = [[UIBarButtonItem alloc]initWithImage:backimg style:UIBarButtonItemStyleBordered target:self action:@selector(backToLastView)];
    self.navigationItem.leftBarButtonItem = backitem;
    
    UIBarButtonItem *manageBtn = [[UIBarButtonItem alloc]initWithTitle:@"管理" style:UIBarButtonItemStyleBordered target:self action:@selector(manageTheItems:)];
    [manageBtn setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont systemFontOfSize:16.0], NSFontAttributeName, nil] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = manageBtn;
}
- (void)backToLastView{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  获取本地的保存的下载完成和下载中的视频数据
 */
- (void)getDownloadedAndDownloadingItems{
    logdebug(@"获取本地数据");
    //获得字典
    NSDictionary *downloadedDic = [NSDictionary dictionaryWithContentsOfFile:DOWNLOADED_PATH];
    NSDictionary *downloadingDic = [NSDictionary dictionaryWithContentsOfFile:DOWNLOADING_PATH];
    /**
     *  解析下载中
     */
    NSArray *Dingarray = [downloadingDic objectForKey:@"videos"];
    
    NSLog(@"%@",downloadingDic);
    
    for (NSDictionary *dic in Dingarray) {
        
        
        NSLog(@"%@",dic);
        //数据模型
        DownloadItem *item = [[DownloadItem alloc]init];
        item.videoID = [dic objectForKey:@"videoId"];
        item.videoUID = [dic objectForKey:@"videoUID"];
        item.videoPath = [dic objectForKey:@"videoPath"];
        item.videoDownloadstatu = [[dic objectForKey:@"videoDownloadStatus"]integerValue];
        item.videoChapter = [dic objectForKey:@"videoChapter"];
        item.videoSection = [dic objectForKey:@"videoSection"];
        item.videoTitle = [dic objectForKey:@"videoTitle"];
        item.videoLectureId = [[dic objectForKey:@"videoLectureid"]integerValue];
        item.videoTeacher = [dic objectForKey:@"videoTeacher"];
        item.videoTotalFileSize = [[dic objectForKey:@"videoTotalFileSize"]integerValue];
        item.videoDownloadedSize = [[dic objectForKey:@"videoDownloadedSize"]integerValue];
        item.videoDownloadProgress = [[dic objectForKey:@"videoDownloadProgress"]floatValue];
        item.videoNum = [[dic objectForKey:@"videoNum"]integerValue];
        item.videoDuration = [[dic objectForKey:@"videoDuration"]integerValue];
        item.videoLectureNum = [dic objectForKey:@"videoLectureNum"];
        item.userMid = [dic objectForKey:@"userMid"];
        logdebug(@"%@",item.userMid);
        //添加
        [downloadingArray addObject:item];
    }
    /**
     *  解析下载完成
     */
    NSArray *DedArray = [downloadedDic objectForKey:@"videos"];
    
    NSLog(@"%@",downloadedDic);
    
    for (NSDictionary *dic in DedArray) {
        logdebug(@"%@",[dic objectForKey:@"array"]);
        [downloadedArray addObject:dic];
    }
}
/**
 *  根据数据初始化的视图
 */
- (void)firstView{
    logdebug(@"初始显示");
    //默认应该是显示下载中的视图
    //除非是空的才会显示已完成
    //全部是空的还是显示下载中
    if (downloadingArray.count==0) {
        if (downloadedArray.count==0) {
            //没有下载完成的
            //都空就还选下载中
            self.offlineView.segmentController.selectedSegmentIndex = 1;
            self.offlineView.noteLabel.text = @"下载队列为空";
        }else{
            self.offlineView.segmentController.selectedSegmentIndex = 0;
            self.offlineView.downloadingTableView.hidden = YES;
            self.offlineView.downloadedTableView.hidden = NO;
        }
    }else{
        self.offlineView.segmentController.selectedSegmentIndex = 1;
        self.offlineView.downloadingTableView.hidden = NO;
        self.offlineView.downloadedTableView.hidden = YES;
    }
    
}
/**
 *  segment点击
 */
-(void)segmentChanged{
    //下载完成界面
    if (self.offlineView.segmentController.selectedSegmentIndex == 0) {
        //隐藏下载中的视图
        self.offlineView.downloadingTableView.hidden = YES;
        //根据列表显示下载完成的视图
        //如果列表是空的则隐藏并且显示提示标签
        if (downloadedArray.count>0) {
            self.offlineView.downloadedTableView.hidden = NO;
        }else{
            self.offlineView.downloadingTableView.hidden = YES;
            self.offlineView.noteLabel.text = @"暂无离线视频";
        }
        
    }else{
        //下载中界面
        //隐藏下载完成界面
        self.offlineView.downloadedTableView.hidden = YES;
        //根据列表的数量是否显示界面
        if (downloadingArray.count>0) {
            self.offlineView.downloadingTableView.hidden = NO;
        }else{
            self.offlineView.downloadingTableView.hidden = YES;
            self.offlineView.noteLabel.text = @"下载队列为空";
        }
    }
}


/****************************************************
 *  tableview相关
 *
 ****************************************************/
#pragma mark - tableview
//行数
//下载完成的行数与每个课程的内容有关
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 100) {
        NSDictionary *dic = [downloadedArray objectAtIndex:section];
        NSArray *array = [dic objectForKey:@"array"];
        if (open[section]==0) {
            return 0;
        }else{
            return array.count;
        }
    }else{
        if (downloadingArray.count == 0) {
            self.offlineView.downloadingTableView.hidden = YES;
        }
        return downloadingArray.count;
    }
}
/**
 *  下载中不进行分组，仅下载完成分组
 *
 *  @param tableView tableView
 *
 *  @return 组数
 */
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView.tag == 100) {
        //下载完成的视图返回跟数组有关
        if (downloadedArray.count == 0) {
            self.offlineView.downloadedTableView.hidden = YES;
        }
        return downloadedArray.count;
    }else{
        return 1;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView.tag == 100) {
        return 60;
    }else{
        return 0;
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView.tag == 100) {
        if (downloadedArray.count>0) {
            //顶部按钮
            UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
            btn.frame= CGRectMake(0, 0, SCREEN_WIDTH, 60);
            btn.tag = section;
            [btn addTarget:self action:@selector(headClick:) forControlEvents:UIControlEventTouchUpInside];
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60)];
            view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1];
            //左部图
            UIView *pointView = [[UIView alloc]initWithFrame:CGRectMake(10, 15, 20, 60)];
            //竖线和豆豆
            UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(9.5, 17, 1, isPad?43:1)];
            line.layer.borderWidth = 1;
            line.layer.borderColor = GreenColor.CGColor;
            
            UILabel *point = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
            point.textColor = GreenColor;
            point.textAlignment = NSTextAlignmentCenter;
            
            [pointView addSubview:point];
            [pointView addSubview:line];
            
            if (open[section]==0) {
                CGRect frame = line.frame;
                frame.size.height = 0;
                line.frame = frame;
                
                point.text = @"●";
                point.font = [UIFont systemFontOfSize:33];
            }else{
                CGRect frame = line.frame;
                frame.size.height = 28;
                line.frame = frame;
                
                point.text = @"○";
                point.font = [UIFont systemFontOfSize:17];
            }
            [view addSubview:pointView];
            
            //间隔线
            UILabel *linespace = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 2)];
            linespace.backgroundColor = [UIColor whiteColor];
            [view addSubview:linespace];
            
            //资料
            NSDictionary *dic = [downloadedArray objectAtIndex:section];
            NSString *name = [dic objectForKey:@"name"];
            
            UILabel *titleLabel = [[UILabel alloc]initWithFrame:RECT(35, 0, SCREEN_WIDTH-20, 45)];
            titleLabel.numberOfLines = 0;
            titleLabel.textColor = [UIColor blackColor];
            titleLabel.font = FONT_SYS_NORMAL;
            titleLabel.backgroundColor = [UIColor clearColor];
            titleLabel.text = name;

            NSArray *ar = [dic objectForKey:@"array"];
            NSDictionary *d = [ar firstObject];
            
            UILabel *teacherLabel = [[UILabel alloc]initWithFrame:CGRectMake(35, 40, SCREEN_WIDTH-20, 15)];
            teacherLabel.text = @"主讲老师:";
            teacherLabel.font = FONT_SYS_LITTLE;
            teacherLabel.textColor = [UIColor darkGrayColor];
            
            UILabel *teacher = [[UILabel alloc]initWithFrame:CGRectMake(100, 40, SCREEN_WIDTH/2, 15)];
            NSString *te = [d objectForKey:@"videoTeacher"];
            teacher.text = te;
            teacher.font = FONT_SYS_LITTLE;
            teacher.textColor = [UIColor orangeColor];
            
            UILabel *lecLabel = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2+30, 40, 40, 15)];
            lecLabel.text= @"课时:";
            lecLabel.font = FONT_SYS_LITTLE;
            lecLabel.textColor = [UIColor darkGrayColor];
            
            UILabel *lecNum = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2+30+35, 40, 50, 15)];
            lecNum.text = [d objectForKey:@"videoLectureNum"];
            lecNum.textColor = [UIColor orangeColor];
            lecNum.font = FONT_SYS_LITTLE;
            
            [view addSubview:titleLabel];
            [view addSubview:teacherLabel];
            [view addSubview:teacher];
            [view addSubview:lecLabel];
            [view addSubview:lecNum];
            view.userInteractionEnabled = NO;
            
            [btn addSubview:view];
            
            return btn;
        }else{
            return nil;
        }
    }else{
        return nil;
    }
}
//收起与展开节列表
- (void)headClick:(UIButton *)btn{
    if (open[btn.tag]==0) {
        open[btn.tag]=1;
        [self.offlineView.downloadedTableView reloadSections:[NSIndexSet indexSetWithIndex:btn.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
    }else{
        open[btn.tag] = 0;
        [self.offlineView.downloadedTableView reloadSections:[NSIndexSet indexSetWithIndex:btn.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 100) {
        return 80;
    }else{
        return 90;
    }
}
//**************cell视图
- (OffLineTableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 100) {
        //下载完成的，需要分组
        OffLineTableViewCell *cell = [[OffLineTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"downloadedcell" tag:0];
        //赋值
        if (downloadedArray.count>0) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[downloadedArray objectAtIndex:indexPath.section]];
            NSArray *dicArray = [dic objectForKey:@"array"];
            NSDictionary *itemDic = [dicArray objectAtIndex:indexPath.row];
            if (indexPath.row==dicArray.count-1) {
                if (isPad) {
                    cell.line.frame = CGRectMake(19.5, 0, 1, 25);
                }else{
                    cell.line.frame = CGRectMake(19.5, 0, 1, 20);
                }
            }
            if ([itemDic objectForKey:@"userMid"] ==nil) {
                [itemDic setValue:[UserMessage sharedUserMessage].userMid forKey:@"userMid"];
            }
            //FIXME:账号权限问题
//            if ([[itemDic objectForKey:@"userMid"] isEqualToString:[UserMessage sharedUserMessage].userMid]) {
//                //一个
//                cell.jurisdiction.hidden = YES;
//                cell.userInteractionEnabled = YES;
//            }else{
//                cell.jurisdiction.hidden = NO;
//                cell.userInteractionEnabled = NO;
//            }
            logdebug(@"%@",[itemDic objectForKey:@"userMid"]);
            cell.titleLabel.text = [itemDic objectForKey:@"videoSection"];
            cell.chapterLabel.text = [itemDic objectForKey:@"videoChapter"];
            cell.teacherLabel.text = [itemDic objectForKey:@"videoTeacher"];
//            cell.sizeLabel.text = [NSString stringWithFormat:@"%0.1fM",(float)[[itemDic objectForKey:@"videoDownloadedSize"]integerValue]/1024/1024];
            cell.durationLabel.text = [NSString stringWithFormat:@"%@分",[itemDic objectForKey:@"videoDuration"]];
            [cell updateCellDownloadStatuesWithStatus:[[itemDic objectForKey:@"videoDownloadStatus"] integerValue]];
            [cell.playBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
//            cell.selectionStyle =UITableViewCellSelectionStyleNone;
        }
        return cell;
    }else{
        //下载中
        OffLineTableViewCell *cell;
        //不要复用，每个都是单独的cell，存入数组调用
        if (downloadingCellArray.count > indexPath.row) {
            //在
            cell = [downloadingCellArray objectAtIndex:indexPath.row];
        }else{
            cell = [[OffLineTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"downloadingcell" tag:1];
            [downloadingCellArray addObject:cell];
        }
        
        if (downloadingArray.count>0) {
            DownloadItem *item = [downloadingArray objectAtIndex:indexPath.row];
            cell.titleLabel.text = item.videoSection;
            cell.lectureLabel.text = item.videoTitle;
            cell.teacherLabel.text = item.videoTeacher;
            cell.durationLabel.text = [NSString stringWithFormat:@"%d分",item.videoDuration];
            [cell updateCellDownloadStatuesWithStatus:item.videoDownloadstatu];
            if (item.videoDownloadstatu == DownloadStatusDownloading){
                cell.statusLabel.text = @"下载中";
            }else if (item.videoDownloadstatu == DownloadStatusPause){
                cell.statusLabel.text = @"已暂停";
            }else if (item.videoDownloadstatu == DownloadStatusFail){
                cell.statusLabel.text = @"请重试";
            }else if (item.videoDownloadstatu == DownloadStatusWait){
                cell.statusLabel.text = @"等待中";
            }
            if (item.videoTotalFileSize>0) {
                item.videoDownloadProgress = (float)item.videoDownloadedSize/item.videoTotalFileSize;
            }
            [cell updateCellProgressWithItem:item];
            [cell.playBtn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
            cell.selectionStyle =UITableViewCellSelectionStyleNone;
        }
        logdebug(@"%@",cell.titleLabel.text);
        return cell;
    }
}
//可编辑
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
//编辑方式（此界面仅限单个删除。为什么？去看Manager）
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
//删除按钮标题
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}
//完成删除
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (tableView.tag == 100) {
            //数组删除
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[downloadedArray objectAtIndex:indexPath.section]];
            logdebug(@"下载完成%@",dic);
            NSMutableArray *array =  [NSMutableArray arrayWithArray:[dic objectForKey:@"array"]];
            NSDictionary *deDic = [array objectAtIndex:indexPath.row];
            NSString *path = [deDic objectForKey:@"videoPath"];
            //删除文件
            [self deleteLocalFile:path];
            logdebug(@"删除文件完成");
            [array removeObjectAtIndex:indexPath.row];
            [dic setObject:array forKey:@"array"];
            [downloadedArray replaceObjectAtIndex:indexPath.section withObject:dic];
            //视图删除
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationLeft];
            //判断标题是否要删除掉
            BOOL sectionDelete = NO;
            if (array.count == 0) {
                //没有了，section也得删除掉
                sectionDelete = YES;
            }
            if (sectionDelete) {
                [downloadedArray removeObjectAtIndex:indexPath.section];
            }
            if (sectionDelete) {
                [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
            }
            //写入本地
            NSDictionary *DIC = [NSDictionary dictionaryWithObjectsAndKeys:downloadedArray,@"videos", nil];
            [DIC writeToFile:DOWNLOADED_PATH atomically:YES];
            [tableView reloadData];
        }else{
            //将数据从数组删除
            DownloadItem *item = [downloadingArray objectAtIndex:indexPath.row];
            NSString * path = item.videoPath;
            if (item.downloader) {
                //删除下载器
                if (item.videoDownloadstatu == DownloadStatusDownloading) {
                    [item.downloader pause];
                    hadDownloading = NO;
                }
                item.downloader = nil;
            }
            logdebug(@"下载中删除");
            //删除文件
            [self deleteLocalFile:path];
            [downloadingArray removeObjectAtIndex:indexPath.row];
            if (downloadingArray.count == 0) {
                tableView.hidden = YES;
                [self segmentChanged];
            }
            //写入本地
            NSDictionary *DIC = [NSDictionary dictionaryWithObjectsAndKeys:[self getDicArrayWithItmesArray:downloadingArray],@"videos", nil];
            BOOL succ = [DIC writeToFile:DOWNLOADING_PATH atomically:YES];
            logdebug(@"%d",succ);
            //视图删除
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationLeft];
            //FIXME:刷新视图，去掉白色的cell
            [tableView reloadData];
        }
    }
}
/**
 *  按钮点击
 *
 *  @param btn btn
 */
-(void)buttonClick:(UIButton *)btn{
    //获取到哪行的数据
    OffLineTableViewCell *cell = nil;
    if (IsIOS7) {
        UIView *view = [btn superview];
        UIView *view2;
        if (IsIOS8) {
            view2 = view;
        }else{
            view2 = [view superview];
        }
        cell =  (OffLineTableViewCell *)[view2 superview];
    }else{
        cell = (OffLineTableViewCell *)[btn superview];
    }
    NSIndexPath *indexPath;
    DownloadItem *item;
    //完成列表的就播放
    if (self.offlineView.segmentController.selectedSegmentIndex == 0) {
        indexPath = [self.offlineView.downloadedTableView indexPathForCell:cell];
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[downloadedArray objectAtIndex:indexPath.section]];
        NSArray *array = [dic objectForKey:@"array"];
        NSDictionary *dicItem = [[array objectAtIndex:indexPath.row]copy];//copy防强引
        //播放
        DWCustomPlayerViewController *player = [[DWCustomPlayerViewController alloc]init];
        player.videoLocalPath = [NSString stringWithFormat:@"%@/%@",DOC_PATH,[dicItem objectForKey:@"videoPath"]];
        player.videoName = [NSString stringWithFormat:@"%@ %@",[dicItem objectForKey:@"videoChapter"],[dicItem objectForKey:@"videoSection"]];
        player.drm = [[dic objectForKey:@"videoUID"]isEqualToString:USER_DRM]?YES:NO;
        player.hidesBottomBarWhenPushed = YES;
        player.playerReturn = ^(NSInteger num){
            logdebug(@"%d",num);
        };
        tmp=1;
        DWCustomPlayerNavViewController *navVC = [[DWCustomPlayerNavViewController alloc]initWithRootViewController:player];
        [self presentViewController:navVC animated:YES completion:nil];
    }else{
        //下载中的判断状态来进行
        indexPath = [self.offlineView.downloadingTableView indexPathForCell:cell];
        item = [downloadingArray objectAtIndex:indexPath.row];
        logdebug(@"item:%@",item.videoSection);
        switch (item.videoDownloadstatu) {
            case DownloadStatusWait:
            {
                if (hadDownloading) {
                    //先找到正在下载的
                    //暂停之前下载的
                    for (int i = 0; i<downloadingArray.count; i++) {
                        DownloadItem *downItem = [downloadingArray objectAtIndex:i];
                        if (downItem.videoDownloadstatu == DownloadStatusDownloading) {
                            //找到对应的cell
                            NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
                            OffLineTableViewCell *downcell = (OffLineTableViewCell *)[self.offlineView.downloadingTableView cellForRowAtIndexPath:index];
                            [self downloadPauseItem:downItem andCell:downcell];
                            break;
                        }
                    }
                    //开始这个
                    hadDownloading = YES;
                    [self startDownloadWithItem:item andCell:cell];
                }else{
                    //没有下载的那就开始啊
                    hadDownloading = YES;
                    [self startDownloadWithItem:item andCell:cell];
                }
            }
                break;
            case DownloadStatusStart:
            {
                //下载开始，那就暂停
                hadDownloading = NO;
                [self downloadPauseItem:item andCell:cell];
            }
                break;
            case DownloadStatusDownloading:
            {
                //下载中，那也暂停
                hadDownloading = NO;
                [self downloadPauseItem:item andCell:cell];
                //暂停计时器
                [timer setFireDate:[NSDate distantFuture]];
            }
                break;
            case DownloadStatusPause:
            {
                //暂停了？那就开始
                //先找到哪个在下载中
                logdebug(@"111");
                if (hadDownloading) {
                    logdebug(@"222");
                    //先找到正在下载的
                    //暂停之前下载的
                    for (int i = 0; i<downloadingArray.count; i++) {
                        DownloadItem *downItem = [downloadingArray objectAtIndex:i];
                        logdebug(@"%@",downItem.videoSection);
                        if (downItem.videoDownloadstatu == DownloadStatusDownloading) {
                            //找到对应的cell
                            logdebug(@"找到了");
                            NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
                            logdebug(@"%d",index.row);
                            OffLineTableViewCell *downcell = (OffLineTableViewCell *)[self.offlineView.downloadingTableView cellForRowAtIndexPath:index];
                            [self downloadPauseItem:downItem andCell:downcell];
                            break;
                        }
                    }
                    //开始这个
                    hadDownloading = YES;
                    [self startDownloadWithItem:item andCell:cell];
                    //开始计时器
                    [timer setFireDate:[NSDate date]];
                }else{
                    //没有下载的那就开始啊
                    hadDownloading = YES;
                    [self startDownloadWithItem:item andCell:cell];
                }
            }
                break;
            case DownloadStatusFail:
            {
                //下载失败了？那就重新开始
                //先找到哪个在下载中
                if (hadDownloading) {
                    //先找到正在下载的
                    //暂停之前下载的
                    for (int i = 0; i<downloadingArray.count; i++) {
                        DownloadItem *downItem = [downloadingArray objectAtIndex:i];
                        if (downItem.videoDownloadstatu == DownloadStatusDownloading) {
                            //找到对应的cell
                            NSIndexPath *index = [NSIndexPath indexPathForRow:i inSection:0];
                            OffLineTableViewCell *downcell = (OffLineTableViewCell *)[self.offlineView.downloadingTableView cellForRowAtIndexPath:index];
                            [self downloadPauseItem:downItem andCell:downcell];
                            break;
                        }
                    }
                    //开始这个
                    hadDownloading = YES;
                    [self startDownloadWithItem:item andCell:cell];
                }else{
                    //没有下载的那就开始啊
                    hadDownloading = YES;
                    [self startDownloadWithItem:item andCell:cell];
                }
            }
                break;
            default:
                break;
        }
    }
}
/*********************************************
 *
 *  下载功能方法
 *********************************************/
/**
 *  添加到下载队列中
 */
- (void)addDownloadQueue:(NSNotification *)notification{
    //解析传来的数据
    NSDictionary *dic = notification.userInfo;
    logdebug(@"下载==%@",dic);
    DownloadItem *item = [[DownloadItem alloc]init];
    item.videoID = [dic objectForKey:@"spark"];
    item.videoUID = [[dic objectForKey:@"drm"]integerValue]==0?USER_FREE:USER_DRM;
    item.videoPath = [NSString stringWithFormat:@"%@.%@",[dic objectForKey:@"spark"],[[dic objectForKey:@"drm"]integerValue]==1?@"pcm":@"mp4"];
    item.videoDownloadstatu = DownloadStatusWait;
    item.videoLectureId = [[dic objectForKey:@"videoId"]integerValue];
    item.videoChapter = [dic objectForKey:@"chapter"];
    item.videoSection = [dic objectForKey:@"section"];
    item.videoTitle = [dic objectForKey:@"lecture"];
    item.videoTeacher = [dic objectForKey:@"teacher"]==[NSNull null]?@"":[dic objectForKey:@"teacher"];
    item.videoTotalFileSize = 0;
    item.videoDownloadedSize = 0;
    item.videoDownloadProgress = 0.0;
    item.videoDuration = [[dic objectForKey:@"duration"]integerValue];
    item.videoNum = [[dic objectForKey:@"videoId"]integerValue];
    item.videoLectureNum = [dic objectForKey:@"lectureNum"];
    item.userMid = [dic objectForKey:@"usermid"];
    //添加
    [downloadingArray addObject:item];
    //刷新视图
    [self.offlineView.downloadingTableView reloadData];
    //保存本地
    NSDictionary *saveDic = [NSDictionary dictionaryWithObjectsAndKeys:[self getDicArrayWithItmesArray:downloadingArray],@"videos", nil];
    [saveDic writeToFile:DOWNLOADING_PATH atomically:YES];
    [self.offlineView.downloadingTableView reloadData];
    //肯定显示
    self.offlineView.downloadingTableView.hidden = YES;
    //添加完应该就可以下载
    [self addTimer];
}
/**
 *  开始下载的方法
 *
 *  @param item 下载模块
 *  @param cell 视图的cell
 */
- (void)startDownloadWithItem:(DownloadItem *)item andCell:(OffLineTableViewCell *)cell{
    //更改状态
    item.videoDownloadstatu = DownloadStatusStart;
    //赋值下载器（根据是否加密来选择）
    DWDownloader *downloader = nil;
    if ([item.videoUID isEqualToString:USER_FREE]) {
        //非加密的
        //保存路径（相对路径）
        NSString *path = [NSString stringWithFormat:@"%@.%@",item.videoID,@"mp4"];
        NSString *docPath = [NSString stringWithFormat:@"%@/%@",DOC_PATH,path];
        item.videoPath = path;
        downloader = [[DWDownloader alloc]initWithUserId:DWACCOUNT_USERID_FREE andVideoId:item.videoID key:DWACCOUNT_APIKEY_FREE destinationPath:docPath];
        
    }else{
        //加密的
        //保存路径（相对路径）
        NSString *path = [NSString stringWithFormat:@"%@.%@",item.videoID,@"pcm"];
        NSString *docPath = [NSString stringWithFormat:@"%@/%@",DOC_PATH,path];
        item.videoPath = path;
        downloader = [[DWDownloader alloc]initWithUserId:DWACCOUNT_USERID andVideoId:item.videoID key:DWACCOUNT_APIKEY destinationPath:docPath];
    }
    item.downloader = downloader;
    downloader.timeoutSeconds = 20;
    //更改状态下载中
    item.videoDownloadstatu = DownloadStatusDownloading;
    //将新数据保存本地
//    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:downloadingArray,@"videos", nil];
//    [dic writeToFile:DOWNLOADING_PATH atomically:YES];
    //启动下载的block
    [self setDownloadBlockWithItem:item andCell:cell];
    [cell updateCellDownloadStatuesWithStatus:item.videoDownloadstatu];
    if (item.videoDownloadstatu == DownloadStatusDownloading){
        cell.statusLabel.text = @"下载中";
    }else if (item.videoDownloadstatu == DownloadStatusPause){
        cell.statusLabel.text = @"已暂停";
    }else if (item.videoDownloadstatu == DownloadStatusFail){
        cell.statusLabel.text = @"请重试";
    }else if (item.videoDownloadstatu == DownloadStatusWait){
        cell.statusLabel.text = @"等待中";
    }
    [downloader start];
}
/**
 *  下载器的block方法
 *
 *  @param item 下载实例
 *  @param cell cell视图
 */
-(void)setDownloadBlockWithItem:(DownloadItem *)item andCell:(OffLineTableViewCell *)cell{
    DWDownloader *downloader = item.downloader;
    /**
     *  进度的block
     *
     *  @param progress                  下载进度
     *  @param totalBytesWritten         已经下载的大小
     *  @param totalBytesExpectedToWrite 还需要下载
     *
     *  @return void
     */
    downloader.progressBlock = ^(float progress, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite){
        //赋值
        item.videoDownloadedSize = totalBytesWritten;
        item.videoTotalFileSize = item.downloader.remoteFileSize;//需要下载的文件在服务器上的大小
        item.videoDownloadProgress = (float)item.videoDownloadedSize/item.videoTotalFileSize;
        //下载进度色值变化
        if (0) {
            cell.progress.progressTintColor = RGBCOLOR(253-item.videoDownloadProgress*188, 106+item.videoDownloadProgress*103, 0+71*item.videoDownloadProgress);
        }
        //更新cell视图的进度
        [cell updateCellProgressWithItem:item];
    };
    /**
     *  下载失败的block
     *
     *  @param error 错误信息
     *
     *  @return void
     */
    downloader.failBlock = ^(NSError *error){
        //打印错误信息
        logdebug(@"%@",error.localizedDescription);
        //更新item的下载状态
        item.videoDownloadstatu = DownloadStatusFail;
        //更新cell的下载状态
        [cell updateCellDownloadStatuesWithStatus:DownloadStatusFail];
        cell.statusLabel.text = @"请重试";
        //下载标签置为NO,让timer寻找下个下载的
        hadDownloading = NO;
    };
    
    /**
     *  下载完成的block
     *
     *  @return void
     */
    downloader.finishBlock = ^(){
        logdebug(@"%@下载完成",item.videoSection);
        //下载标签置为NO,让timer寻找下个下载的
        hadDownloading = NO;
        //更新item下载状态
        item.videoDownloadstatu = DownloadStatusFinish;
        item.videoDownloadedSize = item.downloader.remoteFileSize;
        //数组的操作
        [downloadingArray removeObject:item];
        
        BOOL hadLecture = NO;
        int index = 0;
        //创建字典
        NSString *videoID = item.videoID;
        NSString *videoUID = item.videoUID;
        NSString *videoPath = item.videoPath;
        NSString *videoDownloadstatu = [NSString stringWithFormat:@"%d",item.videoDownloadstatu];
        NSString *videoChapter = item.videoChapter;
        NSString *videoSection = item.videoSection;
        NSString *videoTitle = item.videoTitle;
        NSString *videoLectureid = [NSString stringWithFormat:@"%d",item.videoLectureId];
        NSString *videoTeacher = item.videoTeacher;
        NSString *videoTotalFileSize = [NSString stringWithFormat:@"%d",item.videoTotalFileSize];
        NSString *videoDownloadedSize = [NSString stringWithFormat:@"%d",item.videoDownloadedSize];
        NSString *videoDownloadProgress = [NSString stringWithFormat:@"%f",item.videoDownloadProgress];
        NSString *videoNum = [NSString stringWithFormat:@"%d",item.videoNum];
        NSString *videoDuration =  [NSString stringWithFormat:@"%d",item.videoDuration];
        NSString *videoLectureNum = item.videoLectureNum;
        NSString *usermid = item.userMid;
        NSDictionary *dicA = [NSDictionary dictionaryWithObjectsAndKeys:
                              videoID,@"videoId",
                              videoUID,@"videoUID",
                              videoPath,@"videoPath",
                              videoDownloadstatu,@"videoDownloadStatus",
                              videoChapter,@"videoChapter",
                              videoSection,@"videoSection",
                              videoTitle,@"videoTitle",
                              videoLectureid,@"videoLectureid",
                              videoTeacher,@"videoTeacher",
                              videoTotalFileSize,@"videoTotalFileSize",
                              videoDownloadedSize,@"videoDownloadedSize",
                              videoDownloadProgress,@"videoDownloadProgress",
                              videoNum,@"videoNum",
                              videoDuration,@"videoDuration",
                              videoLectureNum,@"videoLectureNum",
                              usermid,@"userMid",
                              nil];
        NSDictionary *newDic;
        logdebug(@"完成：%@",item.videoTitle);
        for (NSDictionary *dic in downloadedArray) {
            logdebug(@"比对：%@",[dic objectForKey:@"name"]);
            if ([[dic objectForKey:@"name"]isEqualToString:item.videoTitle]) {
                //一个组的
                logdebug(@"有课程");
                hadLecture = YES;
                NSMutableArray * arrayD = [NSMutableArray arrayWithArray:[dic objectForKey:@"array"]];
                BOOL insert = NO;
                for (int i = 0; i<arrayD.count; i++) {
                    NSDictionary *dicD = [arrayD objectAtIndex:i];
                    logdebug(@"%@",dicD);
                    logdebug(@"%ld,%d",(long)item.videoLectureId,[[dicD objectForKey:@"videoLectureid"]intValue]);
                    if (item.videoLectureId<[[dicD objectForKey:@"videoLectureid"]integerValue]) {
                        [arrayD insertObject:dicA atIndex:i];
                        insert = YES;
                        logdebug(@"插入");
                        break;
                    }
                }
                //没能插入就最后加上吧
                if (!insert) {
                    [arrayD addObject:dicA];
                }
                newDic = [NSDictionary dictionaryWithObjectsAndKeys:item.videoTitle,@"name",arrayD,@"array", nil];
                break;
            }
            index ++;
        }
        if (hadLecture) {
            //有课程就替换
            [downloadedArray replaceObjectAtIndex:index withObject:newDic];
        }
        //没有这个课程那就新建一个
        if (!hadLecture) {
            NSMutableArray *arrayC = [NSMutableArray arrayWithObjects:dicA, nil];
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:item.videoTitle,@"name",arrayC,@"array", nil];
            [downloadedArray addObject:dic];
        }
        //本地保存
        NSDictionary *finishedDic = [NSDictionary dictionaryWithObjectsAndKeys:downloadedArray,@"videos", nil];
        NSDictionary *downloadingDic = [NSDictionary dictionaryWithObjectsAndKeys:[self getDicArrayWithItmesArray:downloadingArray],@"videos", nil];
        [finishedDic writeToFile:DOWNLOADED_PATH atomically:YES];
        [downloadingDic writeToFile:DOWNLOADING_PATH atomically:YES];
        //刷新视图
        [self.offlineView.downloadingTableView reloadData];
        [self.offlineView.downloadedTableView reloadData];
        //更新cell
        for (int i = 0; i<downloadingArray.count; i++) {
            OffLineTableViewCell *cell = (OffLineTableViewCell *)[self.offlineView.downloadingTableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
            DownloadItem *item = [downloadingArray objectAtIndex:i];
            [cell updateCellProgressWithItem:item];
        }
        //判断是否隐藏
        if (downloadingArray.count == 0) {
//            [self firstView];
            self.offlineView.segmentController.selectedSegmentIndex = 0;
            self.offlineView.downloadedTableView.hidden = NO;
            self.offlineView.downloadingTableView.hidden = YES;
        }
    };
}
/**
 *  暂停某个下载内容
 *
 *  @param item 下载实例
 *  @param cell cell视图
 */
-(void)downloadPauseItem:(DownloadItem *)item andCell:(OffLineTableViewCell *)cell{
    //暂停
    if (item.downloader) {
        [item.downloader pause];
        item.videoDownloadstatu = DownloadStatusPause;
        [cell updateCellDownloadStatuesWithStatus:DownloadStatusPause];
        cell.statusLabel.text = @"已暂停";
    }else{
        //如果没有下载器
        [self startDownloadWithItem:item andCell:cell];
        [item.downloader pause];
        item.videoDownloadstatu = DownloadStatusPause;
        [cell updateCellDownloadStatuesWithStatus:DownloadStatusPause];
        cell.statusLabel.text = @"已暂停";
        return;
    }
    
}
/**
 *  继续某个下载
 *
 *  @param item 下载实例
 *  @param cell 视图cell
 */
-(void)downloadResumeWithItem:(DownloadItem *)item andCell:(OffLineTableViewCell *)cell{
    if (item.downloader) {
        item.videoDownloadstatu = DownloadStatusDownloading;
        [cell updateCellDownloadStatuesWithStatus:DownloadStatusPause];
        cell.statusLabel.text = @"已暂停";
        [item.downloader resume];
        return;
    }
    //没有下载器就新建一个
    [self startDownloadWithItem:item andCell:cell];
}

/********************************************************
 *  根据下载队列转换成字典数组进行保存
 *
 *  @param array loadqueue
 *
 *  @return dicarray
 */
-(NSArray *)getDicArrayWithItmesArray:(NSArray *)array{
    //创建数组
    NSMutableArray *dicArray = [[NSMutableArray alloc]init];
    for (DownloadItem *item in array) {
        //获取属性
        NSString *videoId = item.videoID;
        NSString *videoUID = item.videoUID;
        NSString * videoPath = item.videoPath;
        NSNumber *videoDownloadStatus = [NSNumber numberWithInt:item.videoDownloadstatu];
        NSString *videoChapter = item.videoChapter;
        NSString *videoSection = item.videoSection;
        NSString *videoTitle = item.videoTitle;
        NSNumber *videoLectureid = [NSNumber numberWithInteger:item.videoLectureId];
        NSString *videoTeacher = item.videoTeacher;
        NSNumber *videoTotalFileSize = [NSNumber numberWithInt:item.videoTotalFileSize];
        NSNumber *videoDownloadedSize = [NSNumber numberWithInt:item.videoDownloadedSize];
        NSNumber *videoDownloadProgress = [NSNumber numberWithInt:item.videoDownloadProgress];
        NSNumber *videoNum = [NSNumber numberWithInteger:item.videoNum];
        NSNumber *videoDuration = [NSNumber numberWithInteger:item.videoDuration];
        NSString *videoLectureNum = item.videoLectureNum;
        NSString *userMid = item.userMid;
        //创建字典
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                             videoId,@"videoId",
                             videoUID,@"videoUID",
                             videoPath,@"videoPath",
                             videoDownloadStatus,@"videoDownloadStatus",
                             videoChapter,@"videoChapter",
                             videoSection,@"videoSection",
                             videoTitle,@"videoTitle",
                             videoLectureid,@"videoLectureid",
                             videoTeacher,@"videoTeacher",
                             videoTotalFileSize,@"videoTotalFileSize",
                             videoDownloadedSize,@"videoDownloadedSize",
                             videoDownloadProgress,@"videoDownloadProgress",
                             videoNum,@"videoNum",
                             videoDuration,@"videoDuration",
                             videoLectureNum,@"videoLectureNum",
                             userMid,@"userMid",
                             nil];
        //添加
        [dicArray addObject:dic];
        
    }
    return dicArray;
}
/****************************************************
 *  计时器 相关
 *
 ****************************************************/
/**
 *  添加网络计时器
 */
-(void)addNetTimer{
    logdebug(@"启动网络监测");
    [netTimer invalidate];
    netTimer = nil;
    netTimer = [NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(checkNetStatues) userInfo:nil repeats:YES];
}
/**
 *  检查网络判断是否下载
 */
-(void)checkNetStatues{
    if ([[[NSUserDefaults standardUserDefaults]valueForKey:WIFI_ONLY]isEqualToString:@"NO"]) {
        //不查
        WIFI = YES;
        return;
    }else{
        if ([[GetNetworkStatues getNetWorkStates]isEqualToString:@"WIFI"]) {
            WIFI = YES;
            return;
        }else{
            //非WIFI而且只在WIFI下下载的情况
            //移除计时器
            [self removeTimer];
            if (hadDownloading) {
                /**
                 *  取到正在下载中的视频
                 */
                NSInteger index = 0;
                DownloadItem *item = nil;
                for (item in downloadingArray) {
                    if (item.videoDownloadstatu == DownloadStatusDownloading||DownloadStatusStart) {
                        break;
                    }
                    index++;
                }
                if (!item) {
                    //没有正在下载的
                    return;
                }
                //获取到cell
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
                OffLineTableViewCell *cell = (OffLineTableViewCell *)[self.offlineView.downloadingTableView cellForRowAtIndexPath:indexPath];
                [self downloadPauseItem:item andCell:cell];
            }
            hadDownloading = NO;
        }
    }
    if (WIFI == YES&&downloadingArray.count>0) {
        [self addTimer];
    }
}
/**
 *  添加计时器
 */
- (void)addTimer{
    logdebug(@"添加主计时器");
    [timer invalidate];
    timer = nil;
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerHandler) userInfo:nil repeats:YES];
}
/**
 *  删除计时器
 */
- (void)removeTimer{
    [timer invalidate];
    timer = nil;
}
- (void)removeNetTimer{
    [netTimer invalidate];
    netTimer = nil;
}
/**
 *  主计时器方法
 */
- (void)timerHandler{
    /**
     *  有在下载的就算了。 这也行，怎么算，万一用户又想删除呢
     */
    if (hadDownloading) {
        logdebug(@"下载中...");
        int had = 0;
        for (DownloadItem *item in downloadingArray) {
            if (item.videoDownloadstatu == DownloadStatusDownloading) {
                logdebug(@"%@%@==%d",item.videoID,item.videoSection,had);
                //获取到cell
                if (had == 1) {
                    [item.downloader pause];
                }else{
                    had = 1;
                }
            }
        }
        return;
    }
    /**
     *  寻找下载列表中的第一个等待状态的视频
     */
    NSInteger index = 0;
    DownloadItem *item = nil;
    for (item in downloadingArray) {
        if (item.videoDownloadstatu == DownloadStatusWait) {
            break;
        }
        index++;
    }
    if (!item) {
        //没有正在下载的
        //是不是要找暂停的呢？
        //后续再说
        logdebug(@"没有任务...");
        return;
    }
    //获取到cell
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    OffLineTableViewCell *cell = (OffLineTableViewCell *)[self.offlineView.downloadingTableView cellForRowAtIndexPath:indexPath];
    //标明已经有下载的了
    hadDownloading = YES;
    //开始下载
    logdebug(@"开始下载");
    logdebug(@"%@%@",indexPath,cell);
    [self startDownloadWithItem:item andCell:cell];
}
//后台
//TODO:后台
-(void)enterBackground:(NSNotification *)notification{
    backTaskId = [[UIApplication sharedApplication]beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication]endBackgroundTask:backTaskId];
    }];
    
    if (backTaskId == UIBackgroundTaskInvalid) {
        logdebug(@"不支持后台运行");
        return;
    }
    foreground = NO;
    __block UIBackgroundTaskIdentifier blockBackTaskId = backTaskId;
    backgroundBlock = ^{
        logdebug(@"申请后台");
        logdebug(@"%f",[UIApplication sharedApplication].backgroundTimeRemaining);
        for (int i = 0; i<30; i++) {
            logdebug(@"%@%d0秒",@"后台",i);
            [NSThread sleepForTimeInterval:10];
            if (foreground) {
                i = 30;
            }
        }
        logdebug(@"结束");
        [[UIApplication sharedApplication]endBackgroundTask:blockBackTaskId];
    };
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), backgroundBlock);
}
//返回前台时去掉后台执行
-(void)enterForeground:(NSNotification *)notification{
    //结束后台请求
    logdebug(@"返回前台，结束后台请求");
    foreground = YES;
//    [[UIApplication sharedApplication]endBackgroundTask:backTaskId];
}

/**************************************************
 *  管理界面
 *
 **************************************************/
-(void)manageTheItems:(UIBarButtonItem *)btn{
    //操作之前的操作，停止所有活动，停止计时器，下载停止，记住在下载哪个然后等返回的时候继续或者重新开始
    //
    //管理界面
    OffLineManagerViewController *managerVC = [[OffLineManagerViewController alloc]init];
    //检查管理哪个界面
    if (self.offlineView.segmentController.selectedSegmentIndex == 0) {
        //下载完成的管理
        managerVC.listArray = downloadedArray;
        managerVC.segIndex = 0;
        managerVC.point = self.offlineView.downloadedTableView.contentOffset;
        if (downloadedArray.count == 0) {
            //空数据不需要管理
            [self.offlineView.noteLabel shake:5 withDelta:6 andSpeed:0.04 shakeDirection:ShakeDirectionVertical];
            return;
        }
    }else{
        //下载中的管理
        managerVC.listArray = downloadingArray;
        managerVC.segIndex = 1;
        managerVC.point = self.offlineView.downloadingTableView.contentOffset;
        if (downloadingArray.count == 0) {
            //空数据不需要管理
            [self.offlineView.noteLabel shake:5 withDelta:6 andSpeed:0.04 shakeDirection:ShakeDirectionVertical];
            return;
        }
    }
    managerVC.hidesBottomBarWhenPushed = YES;
    /**
     *  删除block
     *
     *  @param indexSet    下标集合，用于删除数组
     *  @param deleteArray indexPath数组，用于删除视图
     *
     *  @return void
     */
    managerVC.deleteBlock = ^(NSIndexSet *indexSet,NSArray *deleteArray){
        [self deleteItemsWithIndexSet:indexSet andArray:deleteArray];
    };
    [self.navigationController pushViewController:managerVC animated:NO];
}
/**
 *  删除数组的和plist的
 *
 *  @param indexSet    下标集，删数组元素用
 *  @param deleteArray 删除数组，删视图元素用
 */
-(void)deleteItemsWithIndexSet:(NSIndexSet *)indexSet andArray:(NSArray *)deleteArray{
    //已完成的
    logdebug(@"%@",indexSet);
    if (self.offlineView.segmentController.selectedSegmentIndex == 0) {
        //先获取文件位置然后删除本地视频
        logdebug(@"删除下载完成的");
        for (int i = 0; i<deleteArray.count; i++) {
            NSIndexPath *index = [deleteArray objectAtIndex:i];
            NSDictionary *dic1 = [downloadedArray objectAtIndex:index.section];
            NSArray *array = [dic1 objectForKey:@"array"];
            NSDictionary *dic2 = [array objectAtIndex:index.row];
            NSString *path = [dic2 objectForKey:@"videoPath"];
            [self deleteLocalFile:path];
            logdebug(@"删除%@",path);
        }
        logdebug(@"文件删除完成");
        //数组中删除行
        [indexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
            //遍历indexset
            NSMutableIndexSet *mindexset =  [[NSMutableIndexSet alloc]init];
            for (NSIndexPath *index in deleteArray) {
                if (index.section == idx) {
                    //添加到删除的indexset中
                    [mindexset addIndex:index.row];
                }
            }
            //删除数组中的数组
            NSMutableDictionary *dic1 = [NSMutableDictionary dictionaryWithDictionary:[downloadedArray objectAtIndex:idx]];
            NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:[dic1 objectForKey:@"array"]];
            
            [mutableArray removeObjectsAtIndexes:mindexset];
            [dic1 setObject:mutableArray forKey:@"array"];
            [downloadedArray replaceObjectAtIndex:idx withObject:dic1];
            
        }];
        logdebug(@"数组删除完成");
        //视图删除行
        [self.offlineView.downloadedTableView deleteRowsAtIndexPaths:deleteArray withRowAnimation:UITableViewRowAnimationLeft];
        logdebug(@"视图行删除完成");
        //判断标题是否要删除掉
        logdebug(@"开始删除组--一共%d",downloadedArray.count);
        NSMutableIndexSet *deleteSec = [[NSMutableIndexSet alloc]init];
        for (int i = 0; i<downloadedArray.count; i++) {
            NSDictionary *dic = [downloadedArray objectAtIndex:i];
            NSArray *array = [dic objectForKey:@"array"];
            if (array.count == 0) {
                //添加删除组index
                [deleteSec addIndex:i];
            }
        }
        if (deleteSec.count>0) {
            //删除数组
            [downloadedArray removeObjectsAtIndexes:deleteSec];
            //删除视图
            [self.offlineView.downloadedTableView deleteSections:deleteSec withRowAnimation:UITableViewRowAnimationLeft];
            //
            logdebug(@"删除组完成");
        }
        //写入本地
        NSDictionary *DIC = [NSDictionary dictionaryWithObjectsAndKeys:downloadedArray,@"videos", nil];
        [DIC writeToFile:DOWNLOADED_PATH atomically:YES];
        [self segmentChanged];
    }else{
        //下载中
        //删除视频文件
        logdebug(@"删除下载中");
        //暂停计时器
        [timer setFireDate:[NSDate distantFuture]];
        logdebug(@"暂停计时器");
        NSArray *array = [downloadingArray objectsAtIndexes:indexSet];
        for (DownloadItem *item in array) {
            if (item.downloader) {
                if (item.videoDownloadstatu == DownloadStatusDownloading) {
                    [item.downloader pause];
                    hadDownloading = NO;
                }
                item.videoDownloadstatu = DownloadStatusPause;
                item.downloader = nil;
            }
            NSString *path = item.videoPath;
            [self deleteLocalFile:path];
        }
        //先删除下载中的数组
        [downloadingArray removeObjectsAtIndexes:indexSet];
        logdebug(@"%@",indexSet);
        //在删除视图;
        [self.offlineView.downloadingTableView beginUpdates];
        [self.offlineView.downloadingTableView deleteRowsAtIndexPaths:deleteArray withRowAnimation:UITableViewRowAnimationLeft];
        [self.offlineView.downloadingTableView endUpdates];
        logdebug(@"视图删除");
        //写入本地
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:downloadingArray,@"videos", nil];
        [dic writeToFile:DOWNLOADING_PATH atomically:YES];
        //继续计时器
        [timer setFireDate:[NSDate date]];
    }
}
/**
 *  删除本地的视频
 *
 *  @param filePath 文件路径
 */
-(void)deleteLocalFile:(NSString *)filePath{
    [[NSFileManager defaultManager]removeItemAtPath:[NSString stringWithFormat:@"%@/%@",DOC_PATH,filePath] error:nil];
}
/**
 *  通知全部删除
 *
 *  @param notification
 */
-(void)deleteAllMeidas:(NSNotification *)notification{
    logdebug(@"清除缓存");
    //删除下载完成
    for (int i = 0; i<downloadedArray.count; i++) {
        //
        NSDictionary *dic = [downloadedArray objectAtIndex:i];
        NSArray *array = [dic objectForKey:@"array"];
        for (int j = 0; j<array.count; j++) {
            NSDictionary *dic2 = [array objectAtIndex:j];
            NSString *path = [dic2 objectForKey:@"videoPath"];
            //删除文件
            [[NSFileManager defaultManager]removeItemAtPath:[NSString stringWithFormat:@"%@/%@",DOC_PATH,path] error:nil];
        }
    }
    //下载完成写入plist
    [downloadedArray removeAllObjects];
    NSDictionary *newDic = [NSDictionary dictionaryWithObjectsAndKeys:downloadedArray,@"videos", nil];
    [newDic writeToFile:DOWNLOADED_PATH atomically:YES];
    
    //删除下载中
    [self removeTimer];
    for (int i = 0; i<downloadingArray.count; i++) {
        //
        DownloadItem *item = [downloadingArray objectAtIndex:i];
        //删除文件
        [[NSFileManager defaultManager]removeItemAtPath:[NSString stringWithFormat:@"%@/%@",DOC_PATH,item.videoPath] error:nil];
    }
    //下载中写入plist
    [downloadingArray removeAllObjects];
    NSDictionary *newDic2 = [NSDictionary dictionaryWithObjectsAndKeys:[self getDicArrayWithItmesArray:downloadingArray],@"videos", nil];
    [newDic2 writeToFile:DOWNLOADING_PATH atomically:YES];
    //删除遗留的视频
    NSFileManager *manager = [NSFileManager defaultManager];
    NSEnumerator *enumerator = [[manager subpathsAtPath:DOC_PATH]objectEnumerator];
    for (NSString *path in [enumerator.allObjects copy]) {
        if ([path hasSuffix:@"pcm"]||[path hasSuffix:@"mp4"]) {
            [manager removeItemAtPath:[NSString stringWithFormat:@"%@/%@",DOC_PATH,path] error:nil];
        }
    }
}
/**
 *  保存数据
 *
 *  @param notification notification
 */
-(void)saveDate:(NSNotification *)notification{
    logdebug(@"保存数据");
    //下载中
    NSDictionary *dicdownloading = [NSDictionary dictionaryWithObjectsAndKeys:downloadingArray,@"videos", nil];
    [dicdownloading writeToFile:DOWNLOADING_PATH atomically:YES];
    //已完成
    NSDictionary *dicdownloaded = [NSDictionary dictionaryWithObjectsAndKeys:downloadedArray,@"videos", nil];
    [dicdownloaded writeToFile:DOWNLOADED_PATH atomically:YES];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.offlineView.downloadingTableView.hidden == YES) {
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary:[downloadedArray objectAtIndex:indexPath.section]];
        NSArray *array = [dic objectForKey:@"array"];
        NSDictionary *dicItem = [[array objectAtIndex:indexPath.row]copy];//copy防强引
        //播放
        DWCustomPlayerViewController *player = [[DWCustomPlayerViewController alloc]init];
        player.videoLocalPath = [NSString stringWithFormat:@"%@/%@",DOC_PATH,[dicItem objectForKey:@"videoPath"]];
        player.videoName = [dicItem objectForKey:@"videoSection"];
        player.drm = [[dic objectForKey:@"videoUID"]isEqualToString:USER_DRM]?YES:NO;
        player.hidesBottomBarWhenPushed = YES;
        player.playerReturn = ^(NSInteger num){
        };
        tmp=1;
        DWCustomPlayerNavViewController *navVC = [[DWCustomPlayerNavViewController alloc]initWithRootViewController:player];
        [self presentViewController:navVC animated:YES completion:nil];
    }
}
//-----------------------------
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
